﻿/* 基于WinRar程序的压缩与解压类
 */

/* 未完事项
 * 1、单元测试。
 */
namespace LSLib.Compress
{
    using Microsoft.Win32;
    using System;
    using System.Diagnostics;

    public static class WinRARHelper
    {
        /// <summary>压缩
        /// </summary>
        /// <param name="zipName">要解压的文件名</param>
        /// <param name="zipPath">要压缩的文件目录</param>
        /// <param name="workingDirectory">初始目录</param>
        public static void WinRAR_Compress(string zipName, string zipPath, string workingDirectory)
        {
            string args = string.Format(" A {0} {1}", zipName, zipPath);

            Process winRarProcess = new Process();
            winRarProcess.StartInfo = getWinRarStartInfo(args, workingDirectory);
            winRarProcess.Start();
        }

        /// <summary>解压缩
        /// </summary>
        /// <param name="zipName">要解压的文件名</param>
        /// <param name="zipPath">要解压的文件路径</param>
        public static void WinRAR_Decompress(string zipName, string zipPath)
        {
            string args = string.Format(" X {0} {1}", zipName, zipPath);

            Process winRarProcess = new Process();
            winRarProcess.StartInfo = getWinRarStartInfo(args, null);
            winRarProcess.Start();
        }

        /// <summary>获取 WinRAR 的 ProcessStartInfo
        /// </summary>
        /// <param name="args">获取或设置启动应用程序时要使用的一组命令行参数。</param>
        /// <param name="workingDirectory">获取或设置要启动的进程的初始目录。</param>
        private static ProcessStartInfo getWinRarStartInfo(string args, string workingDirectory)
        {
            if (string.IsNullOrEmpty(args)) throw new ArgumentNullException("args");

            ProcessStartInfo result = new ProcessStartInfo();
            result.FileName = getWinRarFileNameByRegistry();
            result.Arguments = args;
            result.WindowStyle = ProcessWindowStyle.Hidden;
            if (string.IsNullOrEmpty(workingDirectory) == false) result.WorkingDirectory = workingDirectory;
            return result;
        }

        /// <summary>从注册表中获取WinRAR程序的文件路径
        /// </summary>
        /// <returns>WinRAR.exe的文件路径</returns>
        private static string getWinRarFileNameByRegistry()
        {
            string result = string.Empty;
            using (RegistryKey reg = Registry.ClassesRoot.OpenSubKey(@"Applications\WinRAR.exe\Shell\Open\Command"))
            {
                object stmp = reg.GetValue("");
                if (stmp == null) throw new Exception("在注册表中未找到 WinRAR.exe 的相关信息!");

                result = stmp.ToString();
                result = result.Substring(1, result.Length - 7);
            }
            return result;
        }
    }
}
